<template>
  <div class="tag-manage">
    <div class="page-header">
      <h2>标签管理</h2>
      <a-button type="primary" @click="showAddModal">
        <template #icon>
          <PlusOutlined />
        </template>
        新增标签
      </a-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="标签名">
          <a-input v-model:value="searchForm.name" placeholder="请输入标签名" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(record.id)">
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="500px"
    >
      <a-form :model="formState" :rules="rules" ref="formRef" :label-col="{ span: 6 }">
        <a-form-item label="标签名" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入标签名" />
        </a-form-item>
        <a-form-item label="父标签" name="parentId">
          <a-select
            v-model:value="formState.parentId"
            placeholder="请选择父标签（可选）"
            allow-clear
          >
            <a-select-option
              v-for="tag in allTags"
              :key="tag.id"
              :value="tag.id"
              :disabled="isEdit && tag.id === formState.id"
            >
              {{ tag.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { pageTag, addTag, updateTag, deleteTag } from '@/api/tag'
import type { TagVO } from '@/types/api'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'

// 搜索表单
const searchForm = reactive({
  name: undefined,
})

// 表格列定义
const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 100 },
  { title: '标签名', dataIndex: 'name', key: 'name' },
  { title: '父标签ID', dataIndex: 'parentId', key: 'parentId', width: 120 },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    customRender: ({ text }: any) => dayjs(text).format('YYYY-MM-DD HH:mm'),
  },
  { title: '操作', key: 'action', width: 150 },
]

const dataSource = ref<TagVO[]>([])
const allTags = ref<TagVO[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
})

// 弹窗相关
const modalVisible = ref(false)
const modalTitle = ref('新增标签')
const isEdit = ref(false)
const formRef = ref()
const formState = reactive({
  id: undefined as string | undefined,
  name: '',
  parentId: undefined as string | undefined,
})

const rules = {
  name: [{ required: true, message: '请输入标签名', trigger: 'blur' }],
}

// 获取标签列表
const fetchTagList = async () => {
  loading.value = true
  try {
    const res = await pageTag({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    })
    dataSource.value = res.data.list
    pagination.total = parseInt(res.data.total)
  } catch (error) {
    console.error('获取标签列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取所有标签（用于父标签选择）
const fetchAllTags = async () => {
  try {
    const res = await pageTag({
      pageNo: 1,
      pageSize: 100, // 后端限制最大100
    })
    allTags.value = res.data.list
  } catch (error) {
    console.error('获取所有标签失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchTagList()
}

// 重置
const handleReset = () => {
  searchForm.name = undefined
  pagination.current = 1
  fetchTagList()
}

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTagList()
}

// 显示新增弹窗
const showAddModal = () => {
  modalTitle.value = '新增标签'
  isEdit.value = false
  resetForm()
  fetchAllTags() // 打开弹窗时才加载所有标签
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: TagVO) => {
  modalTitle.value = '编辑标签'
  isEdit.value = true
  formState.id = record.id
  formState.name = record.name
  formState.parentId = record.parentId
  fetchAllTags() // 打开弹窗时才加载所有标签
  modalVisible.value = true
}

// 弹窗确定
const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    if (isEdit.value) {
      await updateTag(formState as any)
      message.success('编辑成功')
    } else {
      await addTag(formState as any)
      message.success('新增成功')
    }
    modalVisible.value = false
    fetchTagList()
    // 不需要在这里刷新 allTags，下次打开弹窗时会重新加载
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 弹窗取消
const handleModalCancel = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  formState.id = undefined
  formState.name = ''
  formState.parentId = undefined
  formRef.value?.resetFields()
}

// 删除
const handleDelete = async (id: string) => {
  try {
    await deleteTag({ id })
    message.success('删除成功')
    fetchTagList()
    // 不需要在这里刷新 allTags，下次打开弹窗时会重新加载
  } catch (error) {
    console.error('删除失败:', error)
  }
}

onMounted(() => {
  fetchTagList() // 只在页面加载时获取列表数据
})
</script>

<style scoped>
.tag-manage {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #4a9eff;
  font-size: 24px;
}

.search-bar {
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(26, 31, 58, 0.5);
  border-radius: 8px;
}
</style>

